package ecoll.server;

import java.util.Date;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

import ecoll.client.login.LoginInfo;
import ecoll.client.login.LoginService;

@SuppressWarnings("serial")
public class LoginServiceImpl extends RemoteServiceServlet implements
		LoginService {

	public LoginInfo login(String requestUri) {
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		LoginInfo loginInfo = new LoginInfo();

		if (user != null) {
			loginInfo.setLoggedIn(true);
			loginInfo.setEmailAddress(user.getEmail());
			loginInfo.setNickname(user.getNickname());
			loginInfo.setLogoutUrl(userService.createLogoutURL(requestUri));

			DatastoreService datastore = DatastoreServiceFactory
					.getDatastoreService();
			Key userKey = KeyFactory
					.createKey("UserEntity", user.getNickname());
			Entity userEntity;
			try {
				userEntity = datastore.get(userKey);
				userEntity.setProperty("lastLoginDate", new Date());
				datastore.put(userEntity);
				// put login news
			} catch (EntityNotFoundException e) {
				userEntity = createNewUser(user, datastore);
			}

		} else {
			loginInfo.setLoggedIn(false);
			loginInfo.setLoginUrl(userService.createLoginURL(requestUri));
		}

		// Server.USER = loginInfo;
		return loginInfo;
	}

	private Entity createNewUser(User user, DatastoreService datastore) {
		Entity userEntity = new Entity("UserEntity", user.getNickname());

		userEntity.setProperty("mail", user.getEmail());
		userEntity.setProperty("firstName", "Anonymous");
		userEntity.setProperty("lastName", "Anonymous");
		userEntity.setProperty("photo", null);
		userEntity.setProperty("birthDate", null);
		userEntity.setProperty("description", "");
		userEntity.setProperty("registerDate", new Date());
		userEntity.setProperty("lastLoginDate", new Date());
		userEntity.setProperty("languageLevel", 0);

		datastore.put(userEntity);
		// put welcome news

		return userEntity;
	}

}
